import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/db/DbDAOHelper.dart';

import '../../../beans/buser_model.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../storage/StorageManager.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/NetWorkUtil.dart';
import '../../../utils/tips.dart';

class PhoneLoginController extends GetxController {

  var suffixIconsVisible = false.obs;
  var pwVisible = false.obs;

  var accountController = TextEditingController().obs;
  var validateCodeController = TextEditingController().obs;

  var isSubmitBtnEnable = false.obs;
  var checkBoxChecked = false.obs;


  var countDown = 60.obs;
  var buttonText = '获取验证码'.obs;
  var buttonIsAble = true.obs;

  Timer? _timer;

  var phoneTextFieldEditable = true.obs;

  var scrollController = ScrollController().obs;
  late StreamSubscription<bool> keyboardSubscription;

  @override
  void onInit() {
    super.onInit();

    /*keyboardSubscription = KeyboardVisibilityController().onChange.listen((bool visible) {
      print('Keyboard visibility update. Is visible: $visible');
      if(visible) {
        Future.delayed(Duration(milliseconds: 500), () {
          scrollToBottom();
        });

      }
    });*/

  }

  void scrollToBottom() {
    scrollController.value.animateTo(
      scrollController.value.position.maxScrollExtent,
      duration: const Duration(seconds: 2),
      curve: Curves.easeOut,
    );
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    if (_timer != null) {
      _timer!.cancel();
    }
    scrollController.value.dispose();
    keyboardSubscription.cancel();
    super.onClose();
  }


  void setSuffixIconsVisible(bool visible) {
    suffixIconsVisible.value = visible;
  }

  void onTextFieldChange(v) {
    if (v != null && v != '') {
      suffixIconsVisible.value = true;
    } else {
      suffixIconsVisible.value = false;
    }

    //检查btn提交按钮是否可以点击.
    if(simpleChecking()) {
      isSubmitBtnEnable.value = true;
    } else {
      isSubmitBtnEnable.value = false;
    }
  }

  bool simpleChecking() {
    return accountController.value.text != '' && validateCodeController.value.text != '';
  }

  void onCheckBoxChange() {
    if(simpleChecking()) {
      isSubmitBtnEnable.value = true;
    } else {
      isSubmitBtnEnable.value = false;
    }
  }

  void onTapUserAgreementTask() {

  }

  void onTapPrivacyPolicyTask() {

  }

  void register() {
    Get.toNamed(Routes.REGIST);
  }

  void forgetPasswd() {
    Get.toNamed(Routes.FORGOT_PASSWD);
  }

  void getValidateCode ()  async {
    if (!buttonIsAble.value) {
      return;
    }
    //做权限检查.
    bool isNetWork = await NetWorkUtil.checkNetWorkIsAvailable();
    if (!isNetWork) {
      Tips.showToast('网络不可用.');
      return;
    }

    // 验证邮箱的合法性.
    if(accountController.value.text.isEmpty) {
      Tips.showToast('手机号不能为空.');
      return;
    }


    // 请求接口,发送邮箱验证码.
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.SEND_PHONE_VERIFICATION_CODE, {
      'phone': accountController.value.text,
      'smsmode': 0

    }, NetWorkManager.methodPOST, DataCallBack(
        businessCallBack: (v) {
          buttonIsAble.value = false;
          buttonText.value = countDown.value.toString() +"秒";

          phoneTextFieldEditable.value = false;

          _timer = Timer.periodic(Duration(seconds: 1), (timer) {
            if (countDown.value < 1) {
              timer.cancel();
              buttonIsAble.value = true;
              buttonText.value = '获取验证码';
              countDown.value = 60;
              phoneTextFieldEditable.value = true;
            } else {
              countDown.value = countDown.value - 1;
              buttonText.value = countDown.value.toString() +"秒";
            }
          });
        },
        errorCallBack: (v) {
          Tips.showToast(v);
        }

    ),showLoading: true);

  }

  void login() {
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.PHONE_Login, {
      'phone': accountController.value.text,
      'captcha': validateCodeController.value.text

    }, NetWorkManager.methodPOST, DataCallBack(
        businessCallBack: (v) {
          StorageManager.getStorage().write(AppConst.LOGIN_TOKEN, v['token']);
          StorageManager.getStorage().write(AppConst.LOGIN_USER, v['userInfo']);

          Buser buser = Buser.fromJson(v['userInfo']);
          buser.token = v['token'];

          if(!CommonUtil.hasEnteredAPPBefore()) {
            StorageManager.getStorage().write(AppConst.FIRST_LOGIN, true);
            Get.toNamed(Routes.CHOOSE_DEVICE);
          } else {
            Get.toNamed(Routes.HOME);
          }
        },
        errorCallBack: (v) {
          Tips.showToast(v);
        }

    ),showLoading: true);
  }

}
